package com.yzc.android.utils;

import java.util.List;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;

/**
 * Created by yzc on 16/6/22.
 */
public class MapUtils {
    public static void scaleByPoints(final BaiduMap baiduMap, List<LatLng> points, LatLng center, Boolean animate) {
        if (points == null || points.size() == 0) {
            return;
        }

        if (points.size() == 1) {
            moveToPoint(baiduMap, points.get(0), animate);
            return;
        }

        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngBounds(getBounds(points, center));
        if (animate) {
            baiduMap.animateMapStatus(u);
        }
        else
        {
            baiduMap.setMapStatus(u);
        }
    }

    public static void moveToPoint(final BaiduMap baiduMap, LatLng point, Boolean animate) {
        if (point != null) {
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(point);
            if (animate) {
                baiduMap.animateMapStatus(u);
            }
            else
            {
                baiduMap.setMapStatus(u);
            }
        }
    }

    private static LatLngBounds getBounds(List<LatLng> points, LatLng center) {
        if (points == null || points.size() == 0) {
            return null;
        }

        LatLng first = points.get(0);

        double minLon = first.longitude;
        double maxLon = first.longitude;
        double minLat = first.latitude;
        double maxLat = first.latitude;

        // 计算所有司机的范围
        for (LatLng point : points) {
            double lon = point.longitude;
            double lat = point.latitude;
            if (minLon > lon) {
                minLon = lon;
            }
            if (maxLon < lon) {
                maxLon = lon;
            }
            if (minLat > lat) {
                minLat = lat;
            }
            if (maxLat < lat) {
                maxLat = lat;
            }
        }

        if (center != null) {
            double halfLat = Math.max(Math.abs(maxLat - center.latitude), Math.abs(minLat - center.latitude));
            double halfLon = Math.max(Math.abs(maxLon - center.longitude), Math.abs(minLon - center.longitude));

            maxLat = center.latitude + halfLat;
            minLat = center.latitude - halfLat;
            maxLon = center.longitude + halfLon;
            minLon = center.longitude - halfLon;
        }
        // 144, 68
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        builder.include(new LatLng(minLat, minLon)); // southwest
        builder.include(new LatLng(maxLat, maxLon)); // northeast
        LatLngBounds bounds = builder.build();
        return bounds;
    }



}
